/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.core.config;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.osgi.framework.Bundle;
import org.springframework.core.io.Resource;
import org.springframework.osgi.io.OsgiBundleResourcePatternResolver;

/**
 * @author huangmy
 * @date   2008-3-16
 */
public class PropertiesLocationUtil {
	private final static String[] propertiesNames = new String[]{"*.properties", "*.xml"};
    
	/**
	 * 通过Bundle的路径, 配置文件路径, 获取新的配置文件路径 (etc)
	 * 
	 * @param bundleLocation
	 * @param oldPropertiesLocation
	 * @return
	 */
    public static String createPropertiesLocationFor(String bundleLocation, String oldPropertiesLocation) {		
    	String filename = new File(bundleLocation).getName();
		
    	int endindex = filename.indexOf(".jar");
    	if (endindex < 0) {
    		endindex = filename.indexOf(".war");
    	}
    	
		filename = filename.substring(0, endindex);
		
		filename = "../etc/" + filename;
		
		File file = new File(filename);
		
		if (!file.exists()) {
			file.mkdirs();			
		}
		
		filename = file.getAbsolutePath();
		filename += oldPropertiesLocation;
		
		return filename;
	}
    
    public static List<URL> getBundleProperties(Bundle bundle) {
    	List<URL> props = new ArrayList<URL>();
    	OsgiBundleResourcePatternResolver obrpr = new OsgiBundleResourcePatternResolver(bundle);
    	List<Resource> sources = new ArrayList<Resource>();
    	
		try {
			for (String name : propertiesNames) {
				if (bundle.getLocation().endsWith(".war") && !name.endsWith(".properties")) {
					continue;
				}
				Resource[] resos = obrpr.getResources(name);
				if (resos != null) {
					for (Resource r : resos) {
						sources.add(r);
					}
				}
			}
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		Resource[] resources = sources.toArray(new Resource[sources.size()]);
		
    	if (resources != null) {
    		for (Resource r : resources) {
    			URL url = null;
				try {
					url = r.getURL();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
    			if (url != null) {    				
    				props.add(url);
    			}			
        	}
    	}
    	    	
    	return props;
    }
}
